package cn.sdack.go.users.controller;

import cn.sdack.go.common.entities.BaseEntity;
import cn.sdack.go.common.entities.JsonResult;
import cn.sdack.go.common.entities.users.GroupEntity;
import cn.sdack.go.users.service.GroupService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

/**
 * @author sdack
 * @date 2024/2/15
 */
@RestController
public class GroupController {

    @Autowired
    private GroupService groupService;

    @GetMapping("/group/{id}")
    public JsonResult<?> getById(@PathVariable("id") Long id) {
        try {
            GroupEntity entity = groupService.getById(id);
            return JsonResult.toJson(entity);
        }catch (Exception e) {
            String message = e.getMessage().toString();
            if (message.length() > 100) {
                message = message.substring(0,100);
            }
            return JsonResult.toJson(false,message);
        }
    }

    @PostMapping("/group")
    public JsonResult<?> add(@RequestBody @Validated(BaseEntity.Add.class) GroupEntity param , BindingResult errors) {
        if (errors.hasErrors()) {
            return JsonResult.toJson(false, errors.getAllErrors().get(0).getDefaultMessage());
        }
        try {
            GroupEntity entity = groupService.add(param);
            return JsonResult.toJson(entity);
        }catch (Exception e) {
            String message = e.getMessage().toString();
            if (message.length() > 100) {
                message = message.substring(0,100);
            }
            return JsonResult.toJson(false,message);
        }
    }

    @PutMapping("/group")
    public JsonResult<?> set(@RequestBody @Validated(BaseEntity.Set.class) GroupEntity param , BindingResult errors) {
        if (errors.hasErrors()) {
            return JsonResult.toJson(false, errors.getAllErrors().get(0).getDefaultMessage());
        }

        try {
            GroupEntity entity = groupService.set(param);
            return JsonResult.toJson(entity);
        } catch (Exception e) {
            String message = e.getMessage().toString();
            if (message.length() > 100) {
                message = message.substring(0,100);
            }
            return JsonResult.toJson(false,message);
        }
    }

    @GetMapping("/group/status")
    public JsonResult<?> setState(@RequestParam("g") Long gid,@RequestParam("status") Integer state) {
        try {
            groupService.getById(gid);
            groupService.setStatus(gid,state);
            return JsonResult.toJson(true);
        } catch (Exception e) {
            String message = e.getMessage().toString();
            if (message.length() > 150) {
                message = message.substring(0, 150);
            }
            return JsonResult.toJson(false, message);
        }
    }


}
